package cn.chaozhoubang.vmall.backend.controller.impl;

import cn.chaozhoubang.vmall.backend.annotation.AuthRequire;
import cn.chaozhoubang.vmall.backend.controller.CategoryController;
import cn.chaozhoubang.vmall.backend.mapper.AttributeMapper;
import cn.chaozhoubang.vmall.backend.mapper.CategoryMapper;
import cn.chaozhoubang.vmall.backend.model.SpAttribute;
import cn.chaozhoubang.vmall.backend.model.SpCategory;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Todo 吕志林写
 * @return
 */
@RestController
@RequestMapping("/api/private/v1")
public class CategoryControllerImpl implements CategoryController {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private AttributeMapper attributeMapper;

    private JSONArray buildChilds(SpCategory parent, int type, int level) {
        final QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_level", level);
        wrapper.eq("cat_pid", parent.getCatId());
        final List<SpCategory> list = categoryMapper.selectList(wrapper);
        final JSONArray array = new JSONArray();
        for(SpCategory category: list) {
            final JSONObject object = new JSONObject();
            object.set("cat_id", category.getCatId())
                    .set("cat_name", category.getCatName())
                    .set("cat_pid", category.getCatPid())
                    .set("cat_level", category.getCatLevel())
                    .set("cat_deleted", category.getCatDeleted());
            if(level == 1 && type == 3) {
                final JSONArray childs = buildChilds(category, type, 2);
                object.set("children", childs);
            }
            array.add(object);
        }
        return array;
    }

    private void buildArray(JSONArray result, List<SpCategory> list, int type) {
        for(SpCategory category: list) {
            final JSONObject object = new JSONObject();
            object.set("cat_id", category.getCatId())
                    .set("cat_name", category.getCatName())
                    .set("cat_pid", category.getCatPid())
                    .set("cat_level", category.getCatLevel())
                    .set("cat_deleted", category.getCatDeleted());
            if(type > 1) {
                final JSONArray childs = buildChilds(category, type, 1);
                object.set("children", childs);
            }
            else object.set("children", new JSONArray());
            result.add(object);
        }
    }

    private JSONObject buildData(IPage<SpCategory> page, int type) {
        final JSONObject data = new JSONObject();
        final JSONArray result = new JSONArray();
        data.set("total", page.getTotal());
        data.set("pagenum", page.getCurrent());
        data.set("pagesize", page.getSize());
        List<SpCategory> list = page.getRecords();
        buildArray(result, list, type);
        data.set("result", result);
        return data;
    }

    private JSONArray buildData(List<SpCategory> list, int type) {
        final JSONArray data = new JSONArray();
        buildArray(data, list, type);
        return data;
    }
    private JSONObject buildData() {
        final JSONObject data = new JSONObject();
        return data;
    }
    private JSONObject buildData(SpCategory spCategory) {
        final JSONObject data = new JSONObject();
        data.set("cat_id", spCategory.getCatId())
                .set("cat_name", spCategory.getCatName())
                .set("cat_pid", spCategory.getCatPid())
                .set("cat_level", spCategory.getCatLevel())
                .set("cat_deleted", spCategory.getCatDeleted());
        return data;
    }

    private JSONObject buildMeta(int status, String msg) {
        final JSONObject meta = new JSONObject();
        meta.set("status", status);
        meta.set("msg", msg);
        return meta;
    }

    private JSONObject buildResult(JSONObject meta, JSONObject data) {
        final JSONObject res = new JSONObject();
        res.set("meta", meta);
        res.set("data", data);
        return res;
    }

    private JSONObject buildResult(JSONObject meta, JSONArray data) {
        final JSONObject res = new JSONObject();
        res.set("meta", meta);
        res.set("data", data);
        return res;
    }

    @Override
    @AuthRequire
    @RequestMapping(value = "/categories",produces = "application/json;charset=UTF-8")
    public String getCategories(int type, @RequestParam(defaultValue = "-1") int pagenum, @RequestParam(defaultValue = "-1") int pagesize) {
        QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_pid", 0);
        if(pagenum == -1 || pagesize == -1) {
            final List<SpCategory> list = categoryMapper.selectList(wrapper);
            final JSONArray data = buildData(list, type);
            final JSONObject meta = buildMeta(200, "获取成功");
            return buildResult(meta, data).toString();
        }
        Page<SpCategory> page = new Page<>(pagenum, pagesize);
        IPage<SpCategory> paging = categoryMapper.selectPage(page, wrapper);
        final JSONObject data = buildData(paging, type);
        final JSONObject meta = buildMeta(200, "获取成功");
        return buildResult(meta, data).toString();
    }

    private JSONObject buildInsertData(SpCategory sp){
        final JSONObject object = new JSONObject();
        object.set("cat_id", sp.getCatId())
                .set("cat_name", sp.getCatName())
                .set("cat_pid", sp.getCatPid())
                .set("cat_level", sp.getCatLevel());
        return object;
    }


    @Override
    @PostMapping(value = "/categories", produces = "application/json;charset=UTF-8")
    public String addCategories(@RequestBody String body){
        final JSONObject param = JSONUtil.parseObj(body);
        if(param == null || !param.containsKey("cat_pid") || !param.containsKey("cat_name") ||
            !param.containsKey("cat_level")) {
            return buildResult(buildMeta(400, "参数异常!"), new JSONObject()).toString();
        }
        int cat_pid = (int) param.get("cat_pid");
        int cat_level = (int) param.get("cat_level");
        String cat_name = (String) param.get("cat_name");
        SpCategory spCategory = new SpCategory();
        spCategory.setCatPid(cat_pid);
        spCategory.setCatName(cat_name);
        spCategory.setCatLevel(cat_level);
        int res = categoryMapper.insert(spCategory);
        if(res != 0){
            final QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
            wrapper.eq("cat_name", cat_name);
            final SpCategory sp = categoryMapper.selectOne(wrapper);
            final JSONObject data = buildInsertData(sp);
            final JSONObject meta = buildMeta(201, "添加成功");
            return buildResult(meta,data).toString();
        }else {
            return buildResult(buildMeta(500, "添加失败!"), new JSONObject()).toString();
        }
    }

    //删除分类
    @Override
    @DeleteMapping(value = "/categories/{id}")
    public String deleteCategories(@PathVariable int id) {
        QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_id", id);
        SpCategory spCategory = categoryMapper.selectOne(wrapper);
        if(spCategory == null){
            final JSONObject meta = buildMeta(400, "商品不存在!");
            return  meta.toString();
        }
        int res = categoryMapper.deleteById(id);
        if(res != 0){
            final JSONObject meta = buildMeta(200, "删除成功!");
            final JSONObject data = buildData();
            return buildResult(meta,data).toString();
        }else{
            final JSONObject meta = buildMeta(400, "删除失败!");
            final JSONObject data = buildData();
            return buildResult(meta,data).toString();
        }
    }

    @Override
    @GetMapping(value = "/categories/{id}")
    public String queryCategories(@PathVariable int id) {
        QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_id", id);
        SpCategory spCategory = categoryMapper.selectOne(wrapper);
        final JSONObject data = buildData(spCategory);
        final JSONObject meta = buildMeta(200, "获取成功");
        return buildResult(meta, data).toString();
    }

    @Override
    @PutMapping(value = "/categories/{id}", produces = "application/json;charset=UTF-8")
    public String updateCategories(@PathVariable("id") int id,@RequestBody JSONObject spCategory) {
        final JSONObject param = JSONUtil.parseObj(spCategory);
        QueryWrapper<SpCategory> wrapper = new QueryWrapper<>();
        wrapper.eq("cat_id", id);
        SpCategory spCategory2 = categoryMapper.selectOne(wrapper);
        String cat_name = (String) param.get("cat_name");
        System.out.println(cat_name);
        spCategory2.setCatName(cat_name);
        int res = categoryMapper.updateById(spCategory2);
        if(res != 0){
            final JSONObject meta = buildMeta(200, "编辑成功");
            final JSONObject data = buildData(spCategory2);
            return buildResult(meta,data).toString();
        }else {
            final JSONObject meta = buildMeta(400, "编辑失败");
            final JSONObject data = buildData();
            return buildResult(meta,data).toString();
        }
    }

    @Override
    @GetMapping(value = "/categories/{id}/attributes", produces = "application/json;charset=UTF-8")
    public String getAttribute(@PathVariable int id, String sel) {
        final JSONArray data = new JSONArray();
        final QueryWrapper<SpAttribute> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cat_id", id);
        queryWrapper.eq("attr_sel", sel);
        List<SpAttribute> list = attributeMapper.selectList(queryWrapper);
        for(SpAttribute attribute: list) {
            final JSONObject object = new JSONObject();
            object.set("attr_id", attribute.getAttrId());
            object.set("attr_name", attribute.getAttrName());
            object.set("cat_id", attribute.getCatId());
            object.set("attr_sel", attribute.getAttrSel());
            object.set("attr_write", attribute.getAttrWrite());
            object.set("attr_vals", attribute.getAttrVals());
            data.add(object);
        }
        return buildResult(buildMeta(200, "获取成功"), data).toString();
    }
}
